// index.ts
// 获取应用实例
const app = getApp<IAppOption>()

Component({
  data: {
    mapContext: null as any,
    authorizeModalVisit: false,
    locationWatching: false,
    polyline: [] as any,
    markers: [] as any,
  },

  ready() {
    this.data.mapContext = wx.createMapContext("map");
    wx.offLocationChange();
    wx.stopLocationUpdate();
    this.movetoCurrenctLocation();
  },

  detached() {
    this.stopWatchLocation();
  },

  methods: {
    startWatchLocation () {
      wx.startLocationUpdateBackground({
        success: (res) => {
          console.log("wx.startLocationUpdateBackground success Res: ", res);
          this.setData({ locationWatching: true });

          const _locationChangeFn = (res: any) => {
            console.log('location change', new Date().getTime(), res) 

            let points: any = this.getLocationHistoryPoints();
            points.push({ latitude: res.latitude, longitude: res.longitude })
            console.log("current location history: ", points);

            let lastLocation: any = this.getLastLocationFromHistory();
            
            this.setData({
              polyline: this.data.polyline,
              markers: [{
                id: 1,
                ...lastLocation,
                callout: {
                  ...this.getDefaultColloutProperties(),
                  display: 'ALWAYS' // 'BYCLICK':点击显示; 'ALWAYS':常显
                }
              }]
            });
          }
      
          wx.onLocationChange(_locationChangeFn);
        },

        fail: (res) => {
          console.log("wx.startLocationUpdateBackground fail Res: ", res);
          this.setData({ authorizeModalVisit: true });
        }
      })
    },

    stopWatchLocation() {
      wx.offLocationChange();
      wx.stopLocationUpdate();
      this.setData({ locationWatching: false });
    },

    gotoAuthorize () {
      wx.openSetting();
    },

    closeAuthorizeModal () {
      this.setData({ authorizeModalVisit: false })
    },

    movetoCurrenctLocation () {
      this.data.mapContext.moveToLocation();
    },

    /**
     * 以下是辅助函数，可以不阅读
     */

    getLocationHistoryPoints (): Array<any> {
      if (!this.data.polyline.length) {
        this.data.polyline.push({
          points: [],
          color:"#FA6400", // 线条的颜色
          width: 10, // 宽度
          arrowLine: true, // 是否带箭头
          borderWidth:2 // 线的边框宽度，还有很多参数，请看文档 
        });
      }
      
      return this.data.polyline[0].points as Array<any>;
    },

    getLastLocationFromHistory (): any {
      let points: any = this.getLocationHistoryPoints();
      return points[points.length - 1];
    },

    getDefaultColloutProperties (): any {
      return {
        content: "当前位置",
        color: '#000000',
        bgColor: '#ffffff',
        fontSize: 12,
        borderRadius: 5,
        padding: 5,
        display: 'BYCLICK' // 'BYCLICK':点击显示; 'ALWAYS':常显
      }
    }
  },
})
